//
//  AESManager.swift
//  AIPhotoProcess
//
//  Created by aw031 on 17/10/2025.
//

import Foundation
import CommonCrypto

class AESManager {
    
    static func aesEncryptString(_ content: String, key: String, iv: String) -> String {
        guard let contentData = content.data(using: .utf8),
              let keyData = key.data(using: .utf8),
              let ivData = iv.data(using: .utf8) else {
            return ""
        }
        
        guard let encryptedData = aesEncryptData(contentData, key: keyData, iv: ivData) else {
            return ""
        }
        
        return encryptedData.base64EncodedString(options: .endLineWithLineFeed)
    }
    
    static func aesDecryptString(_ content: String, key: String, iv: String) -> String {
        guard let contentData = Data(base64Encoded: content, options: .ignoreUnknownCharacters),
              let keyData = key.data(using: .utf8),
              let ivData = iv.data(using: .utf8) else {
            return ""
        }
        
        guard let decryptedData = aesDecryptData(contentData, key: keyData, iv: ivData) else {
            return ""
        }
        
        return String(data: decryptedData, encoding: .utf8) ?? ""
    }
    
    static func aesEncryptData(_ contentData: Data, key: Data, iv: Data) -> Data? {
        return cipherOperation(contentData, key: key, iv: iv, operation: CCOperation(kCCEncrypt))
    }
    
    static func aesDecryptData(_ contentData: Data, key: Data, iv: Data) -> Data? {
        return cipherOperation(contentData, key: key, iv: iv, operation: CCOperation(kCCDecrypt))
    }
    
    private static func cipherOperation(_ contentData: Data, key: Data, iv: Data, operation: CCOperation) -> Data? {
        
        let dataLength = contentData.count
        let keyLength = key.count
        let ivLength = iv.count
        
        // 验证 key 和 iv 的长度
        if keyLength != kCCKeySizeAES128 {
            print("Key 长度错误: 需要 \(kCCKeySizeAES128) 字节，实际 \(keyLength) 字节")
            return nil
        }
        
        if ivLength != kCCBlockSizeAES128 {
            print("IV 长度错误: 需要 \(kCCBlockSizeAES128) 字节，实际 \(ivLength) 字节")
            return nil
        }
        
        let cryptLength = dataLength + kCCBlockSizeAES128
        var cryptData = Data(count: cryptLength)
        
        var numBytesEncrypted: size_t = 0
        
        let cryptStatus = cryptData.withUnsafeMutableBytes { cryptBytes in
            contentData.withUnsafeBytes { dataBytes in
                key.withUnsafeBytes { keyBytes in
                    iv.withUnsafeBytes { ivBytes in
                        CCCrypt(operation,
                               CCAlgorithm(kCCAlgorithmAES),
                               CCOptions(kCCOptionPKCS7Padding),
                               keyBytes.baseAddress, keyLength,
                               ivBytes.baseAddress,
                               dataBytes.baseAddress, dataLength,
                               cryptBytes.baseAddress, cryptLength,
                               &numBytesEncrypted)
                    }
                }
            }
        }
        
        if cryptStatus == kCCSuccess {
            cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
            return cryptData
        }
        
        print("加密/解密失败，状态码: \(cryptStatus)")
        return nil
    }
}

